<script lang="ts" setup>
import { computed, h, reactive, ref } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { useDebounceFn } from '@vueuse/core'
import { Button, Col, Divider, Input, message, Row, Select, Space, Spin, Table, TableColumn } from 'ant-design-vue'

import countTabs from '#/adapter/component/count-tabs.vue'
import { useVbenForm } from '#/adapter/form'
import { getDict } from '#/api/common'
import {
  addFactory,
  editFactory,
  ErpBaseSupplyRoleCategory,
  factorylList,
  gitCityList,
  saveFactory,
  setDefaultRowFactory
} from '#/api/factory'
import { getBankList } from '#/api/supply'
import ImageUploader from '#/views/backend/scmGoods/modules/imageUploader.vue'

const emit = defineEmits(['refresh'])
const supply_id = ref(0)


const inputDisabled = ref(false)
const cooperateMode = ref<any>([]) // 合作方式
const productionMode = ref<any>([]) // 生产模式
const productionLevel = [
  { value: 'S', label: 'S' },
  { value: 'A', label: 'A' },
  { value: 'B', label: 'B' },
  { value: 'C', label: 'C' },
]
const payType = [{ value: '月结', label: '月结' }]

const rfidFactory = ref<any>([])
const cityList = ref<any>([])
const activeKey = ref('1')
const tabsList: any = ref([
  { title: '基本信息', value: '1' },
  { title: '财务信息', value: '2' },
  // { title: '供货品类', value: '3' }, 先不做
  { title: '验厂信息', value: '4' },
])
const fetching = ref(false)
const keyword3 = ref('')
const idsArr: any = ref([])
const  currentID =ref(0)
const baseOption = reactive({
  bankList: [], // 银行列表
})

const goodsImages = ref<any>(null) // 成品图片
// 获取银行列表
const fetchBankList = async () => {
  try {
    const res = await getBankList()
    baseOption.bankList = res
  } catch (error) {
    console.error('获取银行列表失败:', error)
  }
}

async function fetchBandOptions({ keyword = '' }: Record<string, any>) {
  const { list } = await ErpBaseSupplyRoleCategory({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'RoleCategoryId',
    initValue: undefined,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.RoleCategory,
    value: item.RoleCategoryId,
  }))
}

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    componentProps: {
      class: 'w-4/5',
    },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'CustomRender',
      fieldName: '_divider',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
    {
      component: 'Input',
      fieldName: 'SupplyCode',
      label: '供应商编码',
      componentProps: {
        disabled: true,
        placeholder: '后台自动生成',
      },
    },
    {
      component: 'Select',
      fieldName: 'Supplytype',
      label: '供应商类别',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请选择类别',
        options: [{ label: '货品供应商', value: 2 }],
      },
      rules: 'required',
    },
    {
      component: 'Select',
      fieldName: 'cooperate_mode',
      label: '合作方式',
      componentProps: {
        mode: 'multiple',
        allowClear: true,
        placeholder: '请选择合作方式',
        options: cooperateMode,
      },
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'SupplyNa',
      label: '供应商简称',
      componentProps: {
        placeholder: '请输入供应商简称',
      },
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'SupplyName',
      label: '公司名称',
      componentProps: {
        placeholder: '请输入公司名称',
      },
      rules: 'required',
    },

    {
      component: 'Input',
      fieldName: 'Supplyman1',
      label: '联系姓名',
      componentProps: {
        placeholder: '请输入联系姓名',
      },
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'Supplytel1',
      label: '手机号码',
      componentProps: {
        placeholder: '请输入手机号码',
      },
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'credit_code',
      label: '公司税号',
      componentProps: {
        placeholder: '社会信用代码(税号)',
      },
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'recommend',
      label: '引荐人员姓名',
      componentProps: {
        placeholder: '请输入引荐人员姓名',
      },
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'recommend_mobile',
      label: '引荐人员电话',
      componentProps: {
        placeholder: '请输入引荐人员电话',
      },
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'inspectors',
      label: '验厂人员姓名',
      componentProps: {
        placeholder: '请输入验厂人员姓名',
      },
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'inspectors_mobile',
      label: '验厂人员电话',
      componentProps: {
        placeholder: '请输入验厂人员电话',
      },
      rules: 'required',
    },

    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchBandOptions,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword3.value = value
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword3.value || undefined,
          },
          showSearch: true,
          allowClear: true,
        }
      },
      fieldName: 'role_category_id',
      label: '权限分类',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'Select',
      fieldName: 'rfid_supply_id',
      label: '芯片供应商',
      componentProps: {
        placeholder: '请选择芯片供应商',
        allowClear: true,
        options: rfidFactory,
      },
      rules: 'selectRequired',
    },
    {
      component: 'Cascader',
      fieldName: 'city',
      label: '省市区域',
      // 调整货品分类的宽度
      componentProps: {
        options: cityList,
        placeholder: '请选择省市区域',
        showSearch: true,
        allowClear: true,
        fieldNames: { label: 'name', value: 'id', children: 'nodes' },
      },
      rules: 'required',
    },
    {
      component: 'Textarea',
      componentProps: {
        allowClear: true,
        class: 'w-full',
        showSearch: true,
        placeholder: '请输入详细地址',
      },
      fieldName: 'address',
      formItemClass: 'col-span-4',
      label: '详细地址',
      rules: 'required',
    },
    {
      component: 'Textarea',
      componentProps: {
        allowClear: true,
        class: 'w-full',
        showSearch: true,
        placeholder: '请输入后台备注',
      },
      fieldName: 'Remark',
      formItemClass: 'col-span-4',
      label: '后台备注',
    },
    {
      component: '_divider1',
      fieldName: '_divider1',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
    {
      component: 'CustomRender',
      fieldName: '_tabs',
      formItemClass: 'col-span-4',
      hideLabel: true,
      dependencies: {
        show(values) {
          return values.activeKey === '2'
        },
        triggerFields: ['activeKey'],
      },
    },
    {
      component: 'Select',
      fieldName: 'production_mode',
      label: '生产模式',
      dependencies: {
        show(values) {
          return values.activeKey === '1'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        mode: 'multiple',
        placeholder: '请选择生产模式',
        allowClear: true,
        options: productionMode,
      },
      rules: 'required',
    },
    {
      component: 'Select',
      fieldName: 'production_level',
      label: '生产级别',
      dependencies: {
        show(values) {
          return values.activeKey === '1'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        placeholder: '请选择生产级别',
        allowClear: true,
        options: productionLevel,
      },
      rules: 'selectRequired',
    },
    {
      component: 'Select',
      fieldName: 'Paytype',
      label: '结算方式',
      dependencies: {
        show(values) {
          return values.activeKey === '1'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        allowClear: true,
        options: payType,
      },
    },
    {
      component: 'Input',
      fieldName: 'legal_person',
      label: '法人姓名',
      dependencies: {
        show(values) {
          return values.activeKey === '1'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        placeholder: '请输入法人姓名',
      },
    },
    {
      component: 'Input',
      fieldName: 'corporate_id_card',
      label: '法人身份证',
      dependencies: {
        show(values) {
          return values.activeKey === '1'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        placeholder: '请输入法人身份证',
      },
    },
    {
      component: 'Input',
      fieldName: 'boss',
      label: '公司负责人',
      dependencies: {
        show(values) {
          return values.activeKey === '1'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        placeholder: '请输入公司负责人',
      },
    },
    {
      component: 'Input',
      fieldName: 'wechat',
      dependencies: {
        show(values) {
          return values.activeKey === '1'
        },
        triggerFields: ['activeKey'],
      },
      label: '微信',
      componentProps: {
        placeholder: '请输入微信',
      },
    },
    {
      component: 'Input',
      fieldName: 'qq',
      label: 'QQ',
      dependencies: {
        show(values) {
          return values.activeKey === '1'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        placeholder: '请输入QQ',
      },
    },
    {
      component: 'Input',
      fieldName: 'website',
      label: '公司网址',
      dependencies: {
        show(values) {
          return values.activeKey === '1'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        placeholder: '请输入公司网址',
      },
    },

    {
      component: '',
      fieldName: 'factory_images',
      formItemClass: 'col-span-4',
      dependencies: {
        show(values) {
          return values.activeKey === '4'
        },
        triggerFields: ['activeKey'],
      },
      hideLabel: true,
    },
    {
      component: 'InputNumber',
      fieldName: 'year_capacity',
      label: '工厂年产量',
      suffix: () => '件',
      dependencies: {
        show(values) {
          return values.activeKey === '4'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        placeholder: '请输入工厂年产量',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'quarter_capacity',
      label: '工厂季产量',
      suffix: () => '件',
      dependencies: {
        show(values) {
          return values.activeKey === '4'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        placeholder: '请输入工厂季产量',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'month_capacity',
      label: '工厂月产量',
      suffix: () => '件',
      dependencies: {
        show(values) {
          return values.activeKey === '4'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        placeholder: '请输入工厂月产量',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'station',
      label: '车位',
      suffix: () => '个',
      dependencies: {
        show(values) {
          return values.activeKey === '4'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        placeholder: '请输入车位',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'sg_month_capacity',
      label: '索歌月产能',
      suffix: () => '件',
      dependencies: {
        show(values) {
          return values.activeKey === '4'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        placeholder: '请输入索歌月产能',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'tail_personnel',
      label: '尾部人员数量',
      suffix: () => '位',
      dependencies: {
        show(values) {
          return values.activeKey === '4'
        },
        triggerFields: ['activeKey'],
      },
      componentProps: {
        placeholder: '请输入尾部人员数量',
      },
    },
  ],
  wrapperClass: 'grid-cols-4',
})
const Text: any = computed(() => {
  return idsArr.value.length > 1 ? '保存并编辑下一项' : '保存'
})
const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  fullscreen: true,
  appendToMain: true,
  fullscreenButton: false,

  onCancel() {
    modalApi.close()
    emit('refresh')
  },
  onConfirm: async () => {
    await baseFormApi.validateAndSubmitForm()
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      const { rowData, view } = modalApi.getData<Record<string, any>>()
      // 拿到字典
      const data = await getDict({ keys: ['productionMode', 'cooperateMode'] })
      cooperateMode.value = Object.entries(data.select_list.cooperateMode).map(([value, label]) => ({
        value,
        label,
      }))
      productionMode.value = Object.entries(data.select_list.productionMode).map(([value, label]) => ({
        value,
        label,
      }))
      // 拿芯片制造商
      const search = [
        {
          field: 'is_rfid_supply',
          val: 1,
          operator: '=',
        },
      ]
      const factory = await factorylList({ search, page: 1, initKey: 'id', select: true })
      rfidFactory.value = factory.list.map((item: any) => ({
        label: item.SupplyNa,
        value: item.id,
      }))
      // 获取城市
      const city = await gitCityList()
      cityList.value = city.nodes
      baseFormApi.setValues({ activeKey: activeKey.value }, false)
      if (view === 'add') {
        inputDisabled.value = false
      } else if (view === 'edit') {
        if (Array.isArray(rowData)) {
          // 如果是多个编辑
          idsArr.value = rowData
          initData(rowData[0])
        } else {
          inputDisabled.value = true
          initData(rowData)
        }
      }

      await fetchBankList()
    }
  },
})
async function initData(rowData: any) {
  editFactory({ id: rowData }).then(async (response) => {
    await baseFormApi.setValues(response.row, false)
    bank_list.value = response.row.bank_list
    supply_id.value = response.row.id
    goodsImages.value = response.row.factory_images

  })
}

const bank_list = ref([])
// 添加银行账户
async function addBank() {
  bank_list.value.push({
    supply_id: 0,
    bank_code: '',
    bank_name: '',
    bank_agency: '',
    user_name: '',
    bank_account: '',
    is_default: 0,
  })
}

// 删除银行账户
const supHandleDel = (index: number) => {
  bank_list.value.splice(index, 1)
}

// 设置默认银行账户
const setDefault= (record: any) => {
  setDefaultRowFactory({ ...record, supply_id: supply_id.value }).then(async (res: any) => {
    if (res.data.code !== 1) {
      message.error(res.data.msg)
      return
    }
    await initData(supply_id.value)
    message.success(res.data.msg)
    emit('refresh')
  })
}

// 保存
async function save() {
  // 验证表单基础信息
  const { valid } = await baseFormApi.validate()
  if (!valid) return
  const urls = goodsImages.value
    ?.map((item: any) => {
      if (item.url) {
        // 清理URL中的反引号和空格
        return item.url.replaceAll(/[`\s]/g, '')
      }
      return ''
    })
    .filter(Boolean) // 过滤掉空字符串
  if (urls && urls.length > 0) {
    baseFormApi.setValues({
      factory_images: urls,
    })
  }
  // 验证银行列表至少有一个
  if (!bank_list.value || bank_list.value.length === 0) {
    message.error('请至少添加一个银行账户')
    return
  }

  // 验证每行银行账户的必填字段
  for (let i = 0; i < bank_list.value.length; i++) {
    const bank = bank_list.value[i]

    // 户名必填
    if (!bank.user_name || bank.user_name.trim() === '') {
      message.error(`第${i + 1}行银行账户：户名为必填项`)
      return
    }

    // 银行账号必填
    if (!bank.bank_account || bank.bank_account.trim() === '') {
      message.error(`第${i + 1}行银行账户：银行账号为必填项`)
      return
    }

    // 银行名称必填
    if (!bank.bank_name || bank.bank_name.trim() === '') {
      message.error(`第${i + 1}行银行账户：银行名称为必填项`)
      return
    }

    // 银行代码必填
    if (!bank.bank_code || bank.bank_code.trim() === '') {
      message.error(`第${i + 1}行银行账户：银行代码为必填项`)
      return
    }

    // 开户行必填
    if (!bank.bank_agency || bank.bank_agency.trim() === '') {
      message.error(`第${i + 1}行银行账户：开行为必填项`)
      return
    }
  }

  const values = await baseFormApi.getValues()
  if (!values.supply_cate) {
    values.supply_cate = []
  }
  values.activeKey = undefined
  const parmas = {
    ...values,
    bank_list: bank_list.value,
  }
  if (values.id) {
    // 如果是多个编辑
    if (idsArr.value.length > 1) {
      saveFactory(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          const index = idsArr.value.indexOf(values.id)
          // 如果找到了对应的值，使用 splice 删除它
          if (index !== -1) {
            idsArr.value.splice(index, 1)
            initData(idsArr.value[0])
          }
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    } else {
      saveFactory(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          modalApi.close()
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    }
  } else {
    addFactory(parmas).then((res: any) => {
      if (res.data.code === 1) {
        message.success(res.data.msg)
        modalApi.close()
        emit('refresh')
      } else {
        message.error(res.data.msg)
      }
    })
  }

  // 这里可以添加后续的保存逻辑
}

function change() {
  baseFormApi.setValues({ activeKey: activeKey.value }, false)
}
</script>

<template>
  <Modal :title="inputDisabled ? '编辑供应商' : '新建供应商'">
    <BaseForm>
      <template #_divider>
        <Divider orientation="left">基础信息</Divider>
      </template>
      <template #_divider1>
        <count-tabs v-model:active-key="activeKey" :list="tabsList" @click-tab="change()" style="width: 700px" :disabled="false" />
      </template>
      <template #_tabs>
        <div style="width: 100%">
          <Button type="primary" style="margin-bottom: 20px; margin-top: 0px" @click="addBank"> 添加 </Button>

          <Table :data-source="bank_list" bordered style="width: 100%" :scroll="{ x: 1200 }" :pagination="false" size="small">
            <TableColumn title="户名" data-index="user_name" key="user_name" width="150">
              <template #default="{ text, record, index }">
                <Input v-model:value="record.user_name" placeholder="请输入户名" />
              </template>
            </TableColumn>

            <TableColumn title="银行账号" data-index="bank_account" key="bank_account" width="180">
              <template #default="{ text, record, index }">
                <Input v-model:value="record.bank_account" placeholder="请输入银行账号" />
              </template>
            </TableColumn>

            <TableColumn title="银行名称" data-index="bank_name" key="bank_name" width="150">
              <template #default="{ text, record, index }">
                <Select v-model:value="record.bank_name" placeholder="请选择银行名称" show-search style="width: 200px">
                  <Select.Option v-for="item in baseOption.bankList" :key="item" :value="item">
                    {{ item }}
                  </Select.Option>
                </Select>
              </template>
            </TableColumn>

            <TableColumn title="银行代码" data-index="bank_code" key="bank_code" width="120">
              <template #default="{ text, record, index }">
                <Input v-model:value="record.bank_code" placeholder="请输入银行代码" />
              </template>
            </TableColumn>

            <TableColumn title="开户行" data-index="bank_agency" key="bank_agency" width="200">
              <template #default="{ text, record, index }">
                <Input v-model:value="record.bank_agency" placeholder="请输入开户行" />
              </template>
            </TableColumn>

            <TableColumn title="默认" data-index="is_default" key="is_default" width="80">
              <template #default="{ text, record, index }">
                <span :class="record.is_default === 1 ? 'text-green-600' : 'text-red-600'">
                  {{ record.is_default === 1 ? '是' : '否' }}
                </span>
              </template>
            </TableColumn>

            <TableColumn title="操作" key="action" width="300">
              <template #default="{ text, record, index }">
                <Space>
                  <Button size="small" danger @click="supHandleDel(index)"> 删除 </Button>
                  <Button type="primary" size="small" @click="setDefault(index)"> 设置为默认 </Button>
                </Space>
              </template>
            </TableColumn>
          </Table>
        </div>
      </template>

      <template #factory_images>
        <Row style="height: 200px; width: 25%; overflow-y: auto">
          <Col span="24">
            <ImageUploader v-model:value="goodsImages" :multiple="true" accept=".jpg,.jpeg,.png,.gif" :max-count="9" upload-text="上传货品图片" />
          </Col>
        </Row>
      </template>
    </BaseForm>
    <template #footer>
      <div class="flex justify-end">
        <Space>
          <Button @click="modalApi.close()">取消</Button>
          <Button type="primary" @click="save()">{{ Text }}</Button>
        </Space>
      </div>
    </template>
  </Modal>
</template>

<style scoped>
.fina-box {
  padding: 10px 0;
}
.fina-btn {
  margin-bottom: 16px;
}
</style>
